package com.example.pokemon_chat_room.ui.notifications;

import static android.content.Context.MODE_PRIVATE;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.pokemon_chat_room.R;
import com.example.pokemon_chat_room.Shop;
import com.example.pokemon_chat_room.adapter.AvatarAdapter;
import com.example.pokemon_chat_room.adapter.MyItemsAdapter;
import com.example.pokemon_chat_room.adapter.MyPokemonAdapter;
import com.example.pokemon_chat_room.adapter.PokeDexAdapter;
import com.example.pokemon_chat_room.databinding.FragmentNotificationsBinding;
import com.example.pokemon_chat_room.pojo.AvatarBase;
import com.example.pokemon_chat_room.pojo.Msg;
import com.example.pokemon_chat_room.pojo.MyItemsDto;
import com.example.pokemon_chat_room.pojo.MyPokemonDto;
import com.example.pokemon_chat_room.pojo.Pokemon;
import com.example.pokemon_chat_room.pokedex;
import com.example.pokemon_chat_room.request.OkHttp;
import com.example.pokemon_chat_room.ui.dashboard.DashboardFragment;
import com.example.pokemon_chat_room.util.CircleImage;
import com.example.pokemon_chat_room.util.MyImageView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class NotificationsFragment extends Fragment {


    private TextView nickname_tv;
    private TextView title_tv;

    private TextView amount_tv;
    private CircleImage avatar_im;

    private Dialog editInfoDialog;

    private Dialog avatarDialog;

    private Dialog myPokemonDialog;

    private Dialog myItemsDialog;

    private Dialog editPasswordDialog;

    private Dialog consultDialog;

    private LinearLayout my_pokemon_base_layout;

    private LinearLayout my_items_base_layout;

    private LinearLayout shop_layout;

    private LinearLayout edit_info_layout;

    private LinearLayout edit_password_layout;

    private LinearLayout consult_layout;

    private Button logout;

    private FragmentNotificationsBinding binding;

    private String nickname;

    private String avatar;

    private String title;

    private String amount;

    private MyReceiver receiver;

    private OkHttp okHttp;







    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        NotificationsViewModel notificationsViewModel =
                new ViewModelProvider(this).get(NotificationsViewModel.class);

        binding = FragmentNotificationsBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        okHttp = new OkHttp();

        IntentFilter filter = new IntentFilter("com.example.pokemon_chat_room.AVATAR");
        receiver = new MyReceiver();
        Objects.requireNonNull(getActivity()).getApplicationContext().registerReceiver(receiver, filter);


        SharedPreferences sharedPreferences = Objects.requireNonNull(getActivity()).getSharedPreferences("user",MODE_PRIVATE);
        nickname = sharedPreferences.getString("nickname", "");
        avatar = sharedPreferences.getString("avatar", "");
        System.out.println(avatar);
        title = getTitle(sharedPreferences.getInt("grade", 0));
        amount = "$" + sharedPreferences.getString("amount", "");
        nickname_tv = root.findViewById(R.id.nickname_tv);
        title_tv = root.findViewById(R.id.title_tv);
        amount_tv = root.findViewById(R.id.amount_tv);
        avatar_im = root.findViewById(R.id.avatar_im);
        edit_info_layout = root.findViewById(R.id.edit_info_layout);
        my_pokemon_base_layout = root.findViewById(R.id.my_pokemon_base_layout);
        my_items_base_layout = root.findViewById(R.id.my_items_base_layout);
        shop_layout = root.findViewById(R.id.shop_layout);
        edit_password_layout = root.findViewById(R.id.edit_password_layout);
        consult_layout = root.findViewById(R.id.consult_layout);
        logout = root.findViewById(R.id.btn_logout);
        edit_info_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openEditInfoDialog();
            }
        });
        my_pokemon_base_layout.setOnClickListener(new View.OnClickListener() {

            class MyDecoration extends RecyclerView.ItemDecoration{
                @Override
                public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                    super.getItemOffsets(outRect, view, parent, state);
                    //outRect.set()中的参数分别对应左、上、右、下的间隔
                    outRect.set(10,10,10,10);
                }
            }

            //
            @Override
            public void onClick(View v) {

                View alertDialogView = getLayoutInflater().inflate(R.layout.my_pokemon_base_layout, null, false);
                RecyclerView recyclerView = alertDialogView.findViewById(R.id.my_poke_list);
                Button close_btn = alertDialogView.findViewById(R.id.close_btn);
                RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 5);
                recyclerView.setLayoutManager(layoutManager);
                recyclerView.addItemDecoration(new MyDecoration());



                OkHttp okHttp = new OkHttp();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SharedPreferences mShared = Objects.requireNonNull(getActivity()).getSharedPreferences("user", MODE_PRIVATE);
                        String token = mShared.getString("token", "");
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("token", token);
                        JSONObject post = null;
                        try {
                            post = okHttp.Post(getContext(), "pokemon-base/getAll", jsonObject);
                            JSONArray data = post.getJSONArray("data");
                            List<MyPokemonDto> list = new ArrayList<>();
                            for (int i = 0; i < data.size(); i++) {
                                list.add(data.getObject(i, MyPokemonDto.class));
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    MyPokemonAdapter adapter = new MyPokemonAdapter(getContext(), list);
                                    recyclerView.setAdapter(adapter);
                                }
                            });
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        System.out.println(post);
                    }
                }).start();

                AlertDialog.Builder editInfoAlertDialog = new AlertDialog.Builder (Objects.requireNonNull(getActivity()));
                editInfoAlertDialog
                        .setView(alertDialogView)
                        .setCancelable(false)
                        .setTitle("我的宝可梦");

                myPokemonDialog = editInfoAlertDialog.show();

                close_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myPokemonDialog.dismiss();
                    }
                });

            }
        });


        my_items_base_layout.setOnClickListener(new View.OnClickListener() {

            class MyDecoration extends RecyclerView.ItemDecoration{
                @Override
                public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                    super.getItemOffsets(outRect, view, parent, state);
                    //outRect.set()中的参数分别对应左、上、右、下的间隔
                    outRect.set(10,10,10,10);
                }
            }
            @Override
            public void onClick(View v) {

                View alertDialogView = getLayoutInflater().inflate(R.layout.my_items_base_layout, null, false);
                RecyclerView recyclerView = alertDialogView.findViewById(R.id.my_items_list);
                Button close_btn = alertDialogView.findViewById(R.id.close_btn);
                RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 5);
                recyclerView.setLayoutManager(layoutManager);
                recyclerView.addItemDecoration(new MyDecoration());

                OkHttp okHttp = new OkHttp();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SharedPreferences mShared = Objects.requireNonNull(getActivity()).getSharedPreferences("user", MODE_PRIVATE);
                        String token = mShared.getString("token", "");
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("token", token);
                        JSONObject post = null;
                        try {
                            post = okHttp.Post(getContext(), "items-base/getAll", jsonObject);
                            JSONArray data = post.getJSONArray("data");
                            List<MyItemsDto> list = new ArrayList<>();
                            for (int i = 0; i < data.size(); i++) {
                                list.add(data.getObject(i, MyItemsDto.class));
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    MyItemsAdapter adapter = new MyItemsAdapter(getContext(), list);
                                    recyclerView.setAdapter(adapter);
                                }
                            });
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        System.out.println(post);
                    }
                }).start();

                AlertDialog.Builder editInfoAlertDialog = new AlertDialog.Builder (Objects.requireNonNull(getActivity()));
                editInfoAlertDialog
                        .setView(alertDialogView)
                        .setCancelable(false)
                        .setTitle("我的道具");

                myItemsDialog = editInfoAlertDialog.show();

                close_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myItemsDialog.dismiss();
                    }
                });
            }
        });

        shop_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), Shop.class);
                getActivity().startActivity(intent);
            }
        });
        edit_password_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View alertDialogView = getLayoutInflater().inflate(R.layout.edit_password_layout, null, false);
                EditText old_password = alertDialogView.findViewById(R.id.old_psw);
                EditText new_password = alertDialogView.findViewById(R.id.new_psw);
                EditText new_password_again = alertDialogView.findViewById(R.id.new_psw_again);
                Button cancel_btn = alertDialogView.findViewById(R.id.cancel_btn);
                Button edit_btn = alertDialogView.findViewById(R.id.edit_btn);
                AlertDialog.Builder editInfoAlertDialog = new AlertDialog.Builder (Objects.requireNonNull(getActivity()));
                editInfoAlertDialog
                        .setView(alertDialogView)
                        .setCancelable(false)
                        .setTitle("修改密码");

                editPasswordDialog = editInfoAlertDialog.show();

                cancel_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        editPasswordDialog.dismiss();
                    }
                });
                edit_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String oldPsw = old_password.getText().toString();
                        String newPsw = new_password.getText().toString();
                        String newPswAgain = new_password_again.getText().toString();

                        if (oldPsw.equals("") || newPsw.equals("") || newPswAgain.equals("")) {
                            Toast.makeText(getContext(), "请完成表单", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (!newPsw.equals(newPswAgain)) {
                            Toast.makeText(getContext(), "两次密码不一致", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("token", sharedPreferences.getString("token", ""));
                        jsonObject.put("oldPsw", oldPsw);
                        jsonObject.put("newPsw", newPsw);

                        okHttp = new OkHttp();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject post = okHttp.Post(getContext(), "user/editPassword", jsonObject);
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getContext(), post.getString("message"), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                    if (post.getInteger("code") == 20005) {
                                        editPasswordDialog.dismiss();
                                    }
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }).start();
                    }
                });
            }
        });

        consult_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View alertDialogView = getLayoutInflater().inflate(R.layout.consult_layout, null, false);
                EditText label_txt = alertDialogView.findViewById(R.id.label_txt);
                RadioGroup type_radio = alertDialogView.findViewById(R.id.type_radio);
                EditText consult_label = alertDialogView.findViewById(R.id.label_txt);
                Button cancel_btn = alertDialogView.findViewById(R.id.cancel_btn);
                Button submit_btn = alertDialogView.findViewById(R.id.edit_btn);
                AlertDialog.Builder editInfoAlertDialog = new AlertDialog.Builder (Objects.requireNonNull(getActivity()));
                editInfoAlertDialog
                        .setView(alertDialogView)
                        .setCancelable(false)
                        .setTitle("客服服务");

                consultDialog = editInfoAlertDialog.show();
                int[] type = {0};

                cancel_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        consultDialog.dismiss();
                    }
                });
                submit_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        okHttp = new OkHttp();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("token", sharedPreferences.getString("token", ""));
                        jsonObject.put("type", type[0]);
                        jsonObject.put("label", label_txt.getText().toString());
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject post = okHttp.Post(getContext(), "log-consult/add", jsonObject);
                                    System.out.println(post);
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getContext(), post.getString("message"), Toast.LENGTH_SHORT).show();

                                            if (post.getInteger("code") == 20003) {
                                                consultDialog.dismiss();
                                            }
                                        }
                                    });

                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }).start();
                    }
                });
                type_radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        System.out.println("checkedId:" + checkedId);
                        if (checkedId == 2131231275) {
                            type[0] = 1;
                        } else {
                            type[0] = 0;
                        }
                    }
                });
            }
        });
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                okHttp = new OkHttp();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("token", sharedPreferences.getString("token", ""));
                        try {
                            okHttp.Post(getContext(), "user/logout", jsonObject);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }).start();

            }
        });
        nickname_tv.setText(nickname);
        title_tv.setText(title);
        amount_tv.setText(amount);
        avatar_im.setImageURL("poke/ava/" + avatar);
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Objects.requireNonNull(getActivity()).getApplicationContext().unregisterReceiver(receiver);
        binding = null;
    }


    public String getTitle(int grade) {
        switch (grade) {
            case 0:
                return "菜鸟训练家";
            case 1:
                return "初级训练家";
            case 2:
                return "中级训练家";
            case 3:
                return "高级训练家";
            case 4:
                return "大师训练家";
            default:
                return "暂无";
        }
    }


    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getExtras().getString("data");
            if (message != null) {
                System.out.println(message);
                Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        avatarDialog.dismiss();
                        avatar_edit.setImageURL("poke/ava/" + message);
                    }
                });
            }
            String message1 = intent.getExtras().getString("free");
            if (message1 != null) {
                myPokemonDialog.dismiss();
            }
        }
    }

    MyImageView avatar_edit;


    public void openEditInfoDialog() {





        View alertDialogView = getLayoutInflater().inflate(R.layout.edit_info_dialog, null, false);
        EditText nickname_edit = alertDialogView.findViewById(R.id.edit_nickname);
        avatar_edit = alertDialogView.findViewById(R.id.edit_avatar);
        Button submit_btn = alertDialogView.findViewById(R.id.edit_btn);
        Button cancel_btn = alertDialogView.findViewById(R.id.cancel_btn);

        submit_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (nickname_edit.getText().toString().equals("")) {
                    Toast.makeText(getContext(), "昵称不为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (nickname_edit.getText().toString().equals(nickname_tv.getText().toString()) && avatar_edit.getImageURL().equals(avatar_im.getImageURL())) {
                    Toast.makeText(getContext(), "请先修改信息再提交", Toast.LENGTH_SHORT).show();
                    return;
                }
                SharedPreferences mShared = Objects.requireNonNull(getActivity()).getSharedPreferences("user", MODE_PRIVATE);
                String token = mShared.getString("token", "");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("avatar", avatar_edit.getImageURL().substring(9));
                jsonObject.put("nickname", nickname_edit.getText().toString());
                jsonObject.put("token", token);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject post = okHttp.Post(getContext(), "user/updateUserInfo", jsonObject);
                            if (post.getInteger("code") == 20005) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getContext(), "修改成功", Toast.LENGTH_SHORT).show();
                                        String imageURL = avatar_edit.getImageURL().substring(9);
                                        String nicknameNew = nickname_edit.getText().toString();
                                        nickname_tv.setText(nicknameNew);
                                        avatar_im.setImageURL(avatar_edit.getImageURL());

                                        SharedPreferences.Editor editor = mShared.edit();// 获得编辑器的对象
                                        editor.putString("avatar", imageURL);
                                        editor.putString("nickname", nicknameNew);
                                        editor.apply();// 提交编辑器中的修改


                                        editInfoDialog.dismiss();
                                    }
                                });
                            }

                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }).start();
            }
        });
        cancel_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editInfoDialog.dismiss();
            }
        });

        nickname_edit.setText(this.nickname);
        avatar_edit.setImageURL("poke/ava/" + this.avatar);



        AlertDialog.Builder editInfoAlertDialog = new AlertDialog.Builder (Objects.requireNonNull(this.getActivity()));
        editInfoAlertDialog
                .setView(alertDialogView)
                .setCancelable(false)
                .setTitle("修改个人信息");

        editInfoDialog = editInfoAlertDialog.show();

        avatar_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View alertDialogView = getLayoutInflater().inflate(R.layout.choose_avatar_layout, null, false);
                RecyclerView recyclerView = alertDialogView.findViewById(R.id.ava_list);
                Button cancel_btn = alertDialogView.findViewById(R.id.cancel_btn);
                RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 3);
                recyclerView.setLayoutManager(layoutManager);
                recyclerView.addItemDecoration(new MyDecoration());



                OkHttp okHttp = new OkHttp();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {

                            List<AvatarBase> avatarBaseList = new ArrayList<>();
                            JSONObject jsonObject = okHttp.Post(getContext(),"avatar-base/getAll", null);
                            JSONArray data = jsonObject.getJSONArray("data");
                            for (int i = 0; i < data.size(); i++) {
                                AvatarBase avatar = (AvatarBase) data.getObject(i, AvatarBase.class);
                                avatarBaseList.add(avatar);
                            }
                            Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    AvatarAdapter adapter = new AvatarAdapter(getContext(), avatarBaseList);
                                    recyclerView.setAdapter(adapter);

                                }
                            });

                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }).start();


                AlertDialog.Builder editInfoAlertDialog = new AlertDialog.Builder (Objects.requireNonNull(getActivity()));
                editInfoAlertDialog
                        .setView(alertDialogView)
                        .setCancelable(false)
                        .setTitle("选择头像");

                avatarDialog = editInfoAlertDialog.show();

                cancel_btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        avatarDialog.dismiss();
                    }
                });
            }

            class MyDecoration extends RecyclerView.ItemDecoration{
                @Override
                public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                    super.getItemOffsets(outRect, view, parent, state);
                    //outRect.set()中的参数分别对应左、上、右、下的间隔
                    outRect.set(10,10,10,10);
                }
            }
        });


    }


}